package org.jetnuke.modules.news;

import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.util.JetUtil;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;

public class RssRead implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(RssRead.class);

	String url;

	public void setUrl(String url) {
		this.url = url;
	}

	public static FeedFetcher feedFetcher = new HttpURLFeedFetcher(
			HashMapFeedInfoCache.getInstance());

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		if (!url.startsWith("http://")) {
			if (!url.startsWith("https://")) {
				url = "http://" + url;
			}
		}
		SyndFeed feed = feedFetcher.retrieveFeed(new URL(url));
		vc.put("ls", feed.getEntries());
		if (feed.getImage() != null)
			vc.put("image", feed.getImage().getUrl());
		vc.put("description", feed.getDescription());
		vc.put("site", feed.getLink());

		StringWriter sw = new StringWriter(1024 * 4);
		try {
			Template t = Velocity.getTemplate("blocks/RssNews/rss.js");
			t.merge(vc, sw);
		} catch (Exception e) {
			logger
					.warn(
							"exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - exception ignored", e); //$NON-NLS-1$
		}
		JetUtil.manageReponseCookies(vc, response);
		response.setContentType("application/x-javascript");
		String txt = sw.toString();

		PrintWriter pw = response.getWriter();
		pw.write(txt);

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

}
